import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';

// 聊天会话删除参数
interface ChatSessionDeleteParams {
  chatId: string;
}

// POST /api/client/chat/sessions/delete - 删除聊天会话
async function handlePost(request: NextRequest): Promise<{ message: string }> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前用户ID
  const userId = authResult.user?.id;
  if (!userId) {
    throw new Error('用户信息不存在');
  }

  // 3. 解析参数
  const { chatId }: ChatSessionDeleteParams = await request.json();

  if (!chatId) {
    throw new Error('聊天会话ID为必填项');
  }

  // 4. 查找并删除聊天会话
  const result = await prisma.chatSession.deleteMany({
    where: {
      chatId,
      userId: userId,
    }
  });

  if (result.count === 0) {
    throw new Error('聊天会话不存在或无权限删除');
  }

  return { message: '聊天会话删除成功' };
}

export const POST = withMiddleware(handlePost);
